<%@ taglib uri="/tags/struts-bean" prefix="bean"%>
<%@ taglib uri="/tags/struts-html" prefix="html"%>
<%@ taglib uri="/tags/struts-logic" prefix="logic"%>
<%@ taglib uri="/tags/core" prefix="c"%>
<%@ taglib uri="/tags/fmt" prefix="fmt"%>
<script type="text/javascript" src="js/utils.js"></script>

<script>

	var emptyForecastList = false;
	<logic:notEmpty name="InstructionPurchaseDetailForm" property="ipdView.customerView.customerId">
		<logic:empty name="InstructionPurchaseDetailForm" property="ipdView.instructionsForecastsDetailView.details">	
			emptyForecastList = true;
		</logic:empty>
	</logic:notEmpty>

	var conUnit = <bean:write name="CON_UNIT"/>;
	var tonsUnit = 1/conUnit;
	var futuresUnit = 1;
	function sumFutures(forma){
		var futures = forma.futures;
   		var tons = forma.tons;
		var futureQuantity = forma.futuresQuantity;
		var futuresSum = 0;
		if( futureQuantity.length == undefined ){
			futuresSum = parseFloat(futureQuantity.value.replace(/,/g, ""));
		}else{
			for (i = 0; i < futureQuantity.length; i++){
				if( trim(futureQuantity[i].value) != "" ){
					futuresSum = futuresSum + parseFloat(futureQuantity[i].value.replace(/,/g, ""));
				}
			}
		}
		futures.value = addCommas(futuresSum);
		tons.value = addCommas(decimales( futuresSum/conUnit,2 ));
	}

	function sumQuantity(forma){
   		var quantityItem = forma.itemQuantity;
   		var quantityCornItem = forma.cornQuantity;
   		var futuresReqTotal = forma.futuresReqTotal;
   		
   		var quantity = 0;
   		var quantityCorn = 0;
   		var futuresReq = 0;
   		
   		var checks = forma.instructionForecastCheck;
   		var  inc = forma.quantity;
   		var  inc2 = forma.quantityCorn;
   		var inc3 = forma.futuresReq;
   		
   		for (i = 0; i < checks.length; i++){
      		if (checks[i].checked){      		
        		quantity = quantity + parseFloat(inc[i].value.replace(/,/g, ""));
        		quantityCorn = quantityCorn + parseFloat(inc2[i].value.replace(/,/g, ""));
        		futuresReq = futuresReq + parseFloat(inc3[i].value.replace(/,/g, ""));
      		}
		}
		
		quantityItem.value = addCommas( decimales( quantity, 2 ) );
		quantityCornItem.value = addCommas( decimales( quantityCorn, 2 ) );
		futuresReqTotal.value = addCommas(parseInt(futuresReq+.99));
	}
	
	function submitSearchCustomer(){
		var form1 = document.getElementById("searchCustomerForm");
		form1.submit();
	}
	
	function submitSearchProduct(){
		var form1 = document.getElementById("searchProductForm");
		form1.submit();
	}
	
	function validate(forma){
		var retVal = false;
		var customerId = document.getElementById("ipdView.customerId").value;		
		var futureTypeId = document.getElementById("ipdView.futureTypeId").value;
		var strategyId = document.getElementById("ipdView.instructionStrategyId").value;
		var strategyTypeId= document.getElementById("ipdView.instructionTypeId").value;
		var status = document.getElementById("ipdView.status").value;
		var futures = forma.futuresQuantity;
		var montSug = forma.montSugQuantity;
		var stopLoss = forma.stopLossQuantity;
		var futuresLength = futures.length;
		
		var tons = forma.tons.value.replace(/,/g, "");
		var cornQuantity = forma.cornQuantity.value.replace(/,/g, "");
		
		futuresUnit = (parseFloat(conUnit)*parseFloat(cornQuantity))+.99;

		var errorsLen = "";
						
		if(parseFloat(tons) > (parseFloat(cornQuantity)+parseFloat(tonsUnit))){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.wrongfuturesnumber"/>';
			errorsLen = errorsLen + ' : <'+parseInt(futuresUnit) +'>\n';
		}
		
		if(customerId == ""){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.customerempty"/>\n';
		}
		if(itemId == ""){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.itemempty"/>\n';
		}
		if(futureTypeId == "-1"){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.typeempty"/>\n';
		}
		if(strategyId == "-1"){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.purchaseestratetyempty"/>\n';			
		}
		if(strategyTypeId == "-1"){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.purchaseestratetytypeempty"/>\n';
		}
		if(status == "-1"){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.statusempty"/>\n';
		}
					
		if(emptyForecastList){		
			errorsLen = errorsLen + '<bean:message key="label.purchases.instructions.detail.commitmentlist.empty"/>\n';
		}
		
		for( var index = 0; index < futuresLength; index++ ){
			
			
			if( trim(futures[index].value) != ''  || trim(montSug[index].value) != ''  ){
			
				if( trim(futures[index].value) == '' || (trim(montSug[index].value) == ''&& strategyId != "1" )){
			
					errorsLen = errorsLen + '\t<bean:message key="label.purchases.instructions.line"/> '+(index+1)+' :\n';
					if( trim(futures[index].value) == '' ){			
						errorsLen = errorsLen +  '\t\t<bean:message key="error.purchases.instructions.future.requiered"/>\n';
					}
					if( trim(montSug[index].value) == '' ){
						if( strategyId != "1" ){
							errorsLen = errorsLen +  '\t\t<bean:message key="error.purchases.instructions.sug.amount"/>\n';
						}
					}else{
						if( parseFloat( montSug[index].value.replace(/,/g, "") ) > parseFloat( stopLoss[index].value.replace(/,/g, "") ) ){

							errorsLen = errorsLen +  '\t\t<bean:message key="error.purchases.instructions.sug.amount.minus.to.stop.loss"/>\n';
						}
					}
				}else{
					if( trim(montSug[index].value) != '' ){
						if( parseFloat( montSug[index].value.replace(/,/g, "") ) > parseFloat( stopLoss[index].value.replace(/,/g, "") ) ){
							errorsLen = errorsLen +  '\t<bean:message key="label.purchases.instructions.line"/> '+(index+1)+' :\n\t\t<bean:message key="error.purchases.instructions.sug.amount.minus.to.stop.loss"/>\n';
						}
					}
				}
			}
		}
						
		if(errorsLen == ""){
			retVal = true;
		}else{
			errorsLen = '<bean:message key="label.common.errors"/>: \n' + errorsLen;
			alert(errorsLen);
		}
		return retVal;
	}
	
	
	function cleanValues(row){  
		if(document.InstructionPurchaseDetailEditForm.futuresQuantity.length != undefined){
			document.InstructionPurchaseDetailEditForm.futuresQuantity[row].value = "";
			document.InstructionPurchaseDetailEditForm.montSugQuantity[row].value = "";
			document.InstructionPurchaseDetailEditForm.stopLossQuantity[row].value = "";
			document.InstructionPurchaseDetailEditForm.accountFuturePeriodId[row].selectedIndex = 0;
			document.InstructionPurchaseDetailEditForm.applicationFuturePeriodId[row].selectedIndex = 0;
			document.InstructionPurchaseDetailEditForm.miniorPrice[row].selectedIndex = 0;
			sumFutures(document.InstructionPurchaseDetailEditForm);
		}
	}

</script>
	<html:form action="/addEditInstructionPurchaseDetail" styleId="mainForm" onsubmit="return validate(this);">
	<html:hidden property="ipdView.row"/>
	
	<table width="99%" align="center" border="0">
		<tr>
			<td colspan="2">
			<table width="100%" align="right" cellpadding="2" cellspacing="1"
				border="0" bgcolor="#CCCCC0">
				<tr>
					<td align="left" class="titulocolumna"><bean:message
						key="label.purchases.instructions.edit.commitment.purchase" /></td>
				</tr>
			</table>
			</td>
		</tr>
		<tr>
			<td colspan="2" align="center">	
				<table align="center" width="100%" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
				<tr>
					<td class="titulocolumna" align="center" width="31%"><bean:message key="label.purchases.instructions.detail.customerdes"/> </td>
					<td class="titulocolumna" align="center" width="31%"><bean:message key="label.purchases.instructions.detail.productdes"/> </td>
					<td class="titulocolumna" align="center" width="9%"><bean:message key="label.purchaseinstructiondetail.type"/> </td>
					<td class="titulocolumna" align="center" width="9%"><bean:message key="label.purchaseinstructiondetail.purchase.strategy"/> </td>
					<td class="titulocolumna" align="center" width="14%"><bean:message key="label.purchaseinstructiondetail.type.strategy"/> </td>
					<td class="titulocolumna" align="center" width="8%"><bean:message key="label.purchaseinstructiondetail.status"/> </td>
				</tr>
				<tr class="columnadatoPar">
					<td align="left"  valign="top">
						<html:hidden property="ipdView.customerView.customerId" styleId="ipdView.customerId"/>
						<html:hidden property="ipdView.customerView.description" /> 
						<bean:write name="InstructionPurchaseDetailEditForm" property="ipdView.customerView.customerId" /> - <bean:write name="InstructionPurchaseDetailEditForm" property="ipdView.customerView.description" />
					</td>
					<td align="left"> 
						<table width="100%" align="center" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
							<c:forEach items="${InstructionPurchaseDetailEditForm.ipdView.productList}" var="productos" varStatus="loopInside">
								<tr class='<c:choose><c:when test="${loopInside.index%2 == 0}"><c:out value="columnadatoPar" /></c:when><c:otherwise><c:out value="columnadatoNon" /></c:otherwise></c:choose>'>
									<td align="center">
										<c:out value="${productos.productId}"></c:out>
									</td>
									<td align="left">
										<c:out value="${productos.description}"></c:out>
									</td>
								</tr>
							</c:forEach>
						</table>
					</td>
					<td class="etiqueta_campo" style="text-align: center;"  valign="top">
						<html:select property="ipdView.futureTypeId" styleId="ipdView.futureTypeId" styleClass="campo_texto"  >
							<html:option value="D"><bean:message key="label.futuretype.D"/></html:option>
							<html:option value="F"><bean:message key="label.futuretype.F"/></html:option>					
						</html:select>
					</td>
					<td class="etiqueta_campo" style="text-align: center;" valign="top" >
						<html:select property="ipdView.instructionStrategyId" styleId="ipdView.instructionStrategyId" styleClass="campo_texto" >
							<html:option value="1"><bean:message key="label.strategyid.1"/></html:option>
							<html:option value="2"><bean:message key="label.strategyid.2"/></html:option>
							<html:option value="3"><bean:message key="label.strategyid.3"/></html:option>
							<html:option value="4"><bean:message key="label.strategyid.4"/></html:option>
						</html:select>		
					</td>
					<td class="etiqueta_campo" style="text-align: center;"  valign="top">
						<html:select property="ipdView.instructionTypeId" styleId="ipdView.instructionTypeId" styleClass="campo_texto"  >
							<html:option value="1"><bean:message key="label.strategytypeid.1"/></html:option>
							<html:option value="2"><bean:message key="label.strategytypeid.2"/></html:option>
							<html:option value="3"><bean:message key="label.strategytypeid.3"/></html:option>
							<html:option value="4"><bean:message key="label.strategytypeid.4"/></html:option>
						</html:select>
					</td>
					<td class="etiqueta_campo" style="text-align: left;"  size="80" valign="top"> 
						<html:select property="ipdView.status" styleId="ipdView.status" styleClass="campo_texto" >
							<html:option value="1"><bean:message key="label.purchaseinstructiondetail.status.1"/></html:option>
						</html:select>			
					</td>
				  </tr>
				</table>
				</td>
			</tr>	
			<tr>
			<td width="40%" align="right" valign="top">
				<table width="95%" align="right" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
					<tr>
						<td colspan="7" align="center" class="titulocolumna">
							<bean:message key="label.purchases.instructions.edit.commitment.purchase.detail"/>
						</td>
					</tr>
					<tr  class="columnadatoPar">
						<td align="right" colspan="2">
							<bean:message key="label.instructionsforecast.totals"/>
						</td>
						<td align="right">
							<html:text styleId="itemQuantity" property="ipdView.itemQuantity" readonly="true" size="8" styleClass="campo_texto_r" />
						</td>
						<td align="right">
							<html:text styleId="cornQuantity" property="ipdView.cornQuantity" readonly="true" size="8" styleClass="campo_texto_r" />
						</td>
						<td align="left" colspan="3">
							<input type="text" name="futuresReqTotal" id="futuresReqTotal" readonly="readonly" size="2" class="campo_texto_r"/>
						</td>
					</tr>
					<tr>
						<td class="titulocolumna" align="center" width="4%">&nbsp;</td>
						<td class="titulocolumna" align="center" width="16%">
							<bean:message key="label.instructionsforecast.period"/>
						</td>	
						<td class="titulocolumna" align="center" width="17%">
							<bean:message key="label.instructionsforecast.quantity"/>
						</td>	
						<td class="titulocolumna" align="center" width="20%">
							<bean:message key="label.instructionsforecast.quantity.corn"/>
						</td>	
						<td class="titulocolumna" align="center" colspan="2">
							<bean:message key="label.instructionsforecast.futures"/>
						</td>	
						<td class="titulocolumna" align="center" width="17%">
							<bean:message key="label.instructionsforecast.current"/>
						</td>
					</tr>
					<c:forEach items="${InstructionPurchaseDetailEditForm.ipdView.instructionsForecastsDetailView.details}" var="detail" varStatus="loop">
						<input type="hidden" id='quantity' name='quantity'  value='<c:out value="${detail.contracted}" />'/>
						<input type="hidden" id='quantityCorn' name='quantityCorn'  value='<c:out value="${detail.cornContracted}" />'/>
						<input type="hidden" id='futuresReq' name='futuresReq'  value='<c:out value="${detail.futures}" />'/>
						<tr <c:if test="${(loop.index%2)==0}">class="columnadatoPar" </c:if><c:if test="${(loop.index%2)!=0}">class="columnadatoNon"</c:if>>
							<td>
								<input type='checkbox' 
								onclick="sumQuantity(this.form)" 
								id="instructionForecastCheck" 
								name='ipdView.instructionsForecastsDetailView.checked'  
								<c:if test="${detail.forecastAdded==1 || detail.forecastChecked == 1}" ><c:out value="checked"/></c:if> 
								value='<c:out value="${loop.index}"/>' />
							</td>
							<td align="center">			
								<a href="showForecastByPeriodEdit.do?month=<c:out value="${detail.month}" />&year=<c:out value="${detail.year}" />&customerId=<c:out value="${detail.customerId}" />&instructionPurchaseDetailId=-1">
										<c:out value="${detail.year}" />.<fmt:formatNumber maxIntegerDigits="2" minIntegerDigits="2" pattern="##" value="${detail.month}"></fmt:formatNumber>
									</a>
							</td>
							<td align="right">
								<c:out value="${detail.contracted}" />
							</td>
							<td align="right">
								<c:out value="${detail.cornContracted}" />
							</td>
							<td width="10%" align="right">
								<c:out value="${detail.futuresFloored}" />
							</td>
							<td width="14%"  align="right">
								(<c:out value="${detail.futures}" />)
							</td>
							<td>
								<c:if test="${detail.forecastAdded==1}" ><c:out value="${detail.actual}" /></c:if>
							</td>
						</tr>
						</c:forEach>
					</table>
			</td>
			<td width="60%" align="left" valign="top">
			<!-- FUTURES TABLA DERECHA -->
				<table width="450px" align="left" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
					<tr>
						<td colspan="7" align="center" class="titulocolumna">
							<bean:message key="label.purchases.instructions.label"/>
						</td>
					</tr>
					<tr class="columnadatoPar">
						<td align="center" >
							<html:text styleId="futures" property="ipdView.futures" readonly="true" size="3" styleClass="campo_texto_r" />
							<html:hidden styleId="tons" property="ipdView.tons" />
						</td>
						<td colspan="6" align="left"><bean:message key="label.instructionsforecast.totals"/></td>
					</tr>
					<tr>
						<td class="titulocolumna">
							<bean:message key="menu.module.corn.sub.future"/>
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.price"/>												
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.furchase.period"/>
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.furchase.application"/>												
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.minor.price"/>												
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.stoploss"/>								
						</td>
						<td class="titulocolumna">
							&nbsp;
						</td>
					</tr>														   
						<logic:notEmpty name="InstructionPurchaseDetailForm" property="ipdView.instructionsFuturesView">
							<c:forEach items="${InstructionPurchaseDetailEditForm.ipdView.instructionsFuturesView}" var="row" varStatus="loop">
								<tr <c:if test="${(loop.index%2)==0}"> class="columnadatoPar"</c:if> <c:if test="${(loop.index%2)!=0}">class="columnadatoNon"</c:if>>
									<td align="center">
									<html:hidden name="row" property="purchaseInstructionFutureId"/>
									<html:hidden name="row" property="purchaseInstructionDetailId"/>					
										<input type="hidden" style="text-align: right;" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].purchaseInstructionDetailId' value='<c:out value="${row.purchaseInstructionDetailId}"/>' />
										<input type="text" style="text-align: right;" onblur="sumFutures(this.form)"  id="futuresQuantity" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].quantity' value='<logic:notEqual name="row" property="quantity" value="0"><c:out value="${row.quantity}"/></logic:notEqual>' class="campo_texto" onfocus="this.select();" onkeydown="return (numeric(event, 0) && noPaste(event, this));" onkeyup="extractNumber(this,2,false);" size="3">
									</td>
									<td align="center">						
										<input id="montSugQuantity" type="text" style="text-align: right;" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].price' onfocus="this.select();" value='<c:out value="${row.price}"/>' class="campo_texto" onfocus="this.select();" onkeydown="return (numeric(event, 1) && noPaste(event, this));" onkeyup="extractNumber(this,4,false);" size="5">
										
									</td>
									<td align="center">
										<select id="accountFuturePeriodId" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].accountFuturePeriodId' class="campo_texto" >
											<c:forEach var="row1" items="${InstructionPurchaseDetailForm.ipdView.instructionsFuturesView[loop.index].accountPeriod}">	
												<option	
													value='<c:out value="${row1.periodId}" />'
													<c:if test="${row1.selected}" >selected</c:if> >
													<c:out value="${row1.periodName}" /> 
												</option>
											</c:forEach>
										</select>													
									</td>
									<td align="center">	
										<select id="applicationFuturePeriodId" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].applicationFuturePeriodId' class="campo_texto" >							
											<c:forEach var="row2" items="${InstructionPurchaseDetailForm.ipdView.instructionsFuturesView[loop.index].applicationPeriod}">
												<option	
													value='<c:out value="${row2.periodId}" />'
													<c:if test="${row2.selected}" >selected</c:if> >
													<c:out value="${row2.periodName}" /> 
												</option>								
											</c:forEach>
										</select>										
									</td>
									<td align="center">
									  <select id="miniorPrice" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].miniorPrice' class="campo_texto" >
									  	<option value="Y" 	<c:if test="${row.miniorPrice == 'Y'}" >selected</c:if> >
									  		<bean:message key="label.common.yes" />
									  	</option>
									  	<option value="N" <c:if test="${row.miniorPrice == 'N'}" >selected</c:if> ><bean:message key="label.common.no" /></option>
									  </select>					  					  
									</td>
									<td align="center">						
										<input type="text" id="stopLossQuantity" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].stopLoss' onfocus="this.select();" value='<c:out value="${row.stopLoss}"/>' style="text-align: right;" onkeydown="return (numeric(event, 1) && noPaste(event, this));" onkeyup="extractNumber(this,4,false);" class="columnanumero" size="5" />
									</td>
									<td>
										<a href="#" onclick='cleanValues("<c:out value="${loop.index}"/>")'>
											<img alt="<bean:message key="login.button.clear" />" src="images/erase.png" border="0">
										</a>
									</td>
								</tr>	
							</c:forEach>
						</logic:notEmpty>		
					</table>
			<!-- FUTURES TABLA DERECHA-->
			</td>
		</tr>
</table>
<table>
	<tr>
		<td colspan="10" align="center" class="columnadatoPar">
			<html:submit styleClass="boton" property="mainForm"><bean:message key="label.common.save"/></html:submit>
			<html:button styleClass="boton" property="backButton" onclick="location.href = 'goInstructionPurchaseHeader.do'"><bean:message key="label.common.cancel"/></html:button>
		</td>	
	</tr>
</table>
</html:form>
<html:form action="/ipdSearchCustomer" styleId="searchCustomerForm">
</html:form>
<html:form action="/ipdSearchProduct" styleId="searchProductForm">
</html:form>
<script>
	sumQuantity(document.InstructionPurchaseDetailEditForm);
</script>